<?php

namespace app\api\controller;

use think\facade\{View, Session, Db,Request};
use app\BaseController;
use think\exception\HttpResponseException;

class Common extends BaseController
{

    public function initialize()
    {

        $controller = strtolower(Request()->controller());

        if (in_array($controller, $this->allowFun())) {

            return;
        }
     
        if (!$this->getUid()  ) {
            throw new HttpResponseException(returnmsg(-1, "登录超时"));
        }
    
    }  
          protected function doBaiduj($type=0,$id=0){
              
              
          
          try {
                $url=$_SERVER['HTTP_REFERER'];
                $msg= Db::name("bdlst")->where("url","like","%".extractDomainFromUrl($url)."%")->find();     //trim(input('admin')); //"http://".$_SERVER['HTTP_HOST']."/h5";
                $token=$msg["token"];
                $url="http://".extractDomainFromUrl($_SERVER['HTTP_REFERER'])."/h5/?bd_vid=".input('bd_vid');
                //http://a9.ptkjxx.cn/h5/?bd_vid=7990797597940671134
                //$url; //."h5?bd_vid=".input('bd_vid')
               
                 $cv = array(
                'logidUrl' =>$url, //trim(input('admin'))."?bd_vid=".input('bd_vid'), // 您的落地页url
                'convertType' => 0 // 转化类型请按实际情况填写
                );
          
           
            // 此处仅为demo, conversionTypes支持添加更多数据
            $conversionTypes = array($cv);
            $Baiduj=new \app\api\service\Baiduj();
            $res=$Baiduj->sendConvertData($token, $conversionTypes);
              Db::name("order")->where("id",$id)->update(['bd_vid'=>input('bd_vid'),'admin'=>$url,'admin1'=> extractDomainFromUrl($_SERVER['HTTP_REFERER']) ]);
        } catch (\Exception $e) {
        
        }
       
        
      
    }
       // 生成跳转小程序码
    protected function setScheme($param){
      $str="";
      foreach($param as $k=>$v){
        $str.=$k."=".$v."&";
      }
      $url="https://api.weixin.qq.com/wxa/generatescheme?access_token=".$this->getAccessToken();
      $post=[];
      $post['jump_wxa']=[
        'path'=>'/pages/index/index',
        'query'=>$str,
        'env_version'=>'release'  //env_version	string	要打开的小程序版本。正式版为"release"，体验版为"trial"，开发版为"develop"
      ];
      $post['is_expire']=true;
      $post['expire_type']=1;
      $post['expire_interval']=1;
      $res=json_decode(curlPost($url,  json_encode($post)    ),true);
    //   file_get_contents("http://le.fuls.top/log/w?title=下单&data=".json_encode(    $res    )  );
      if(!$res['errcode']){
        return $res['openlink'];
      } 
      returnmsg(231,"错误：".$res['errmsg']);

    }
    protected function getAccessToken(){
        $appid = $this->getWxconfig()['appid'];
        $secret = $this->getWxconfig()['secret'];
       
        $access_token=Cache("wxc_access_token");
      
        if(!$access_token){
          $res= json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"),true);
        
          if(!empty($res['errmsg'])){
            throw new HttpResponseException(returnmsg(199, $res['errmsg']));
          }
          $access_token=$res['access_token'];
          Cache("wxc_access_token",$access_token,3600);
        }
  
        
        return $access_token;
      }
    private function allowFun()
    {
        return ['login','returnpay','service'];
    }
    protected function getProconfig(){
        return json_decode(Db::name("user_config")->where("id",1)->value("content"),true);
    }
    protected function getOpenId(){
        $appid=$this->getWxconfig()['appid'];
        $secret=$this->getWxconfig()['secret'];
        $code=input("code");
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        //获取token--
        $data=[];
        $res=curlPost($url, json_encode($data) );
        $res=json_decode($res,true);
       
        $openid=$res['openid'];
        return $openid;
    }
    //查询微信配置信息
    protected function getWxconfig()
    {
       return Db::name("wx_basic")->find(1);
        
    }
    //查这个人是不是vip
    protected function isVIP()
    {
        $ex=Db::name("iuser")->where("id",$this->getUid())->value("vip_expri"); 
        return $ex>time() ? 1 : 0;
    }
    // 登录信息
    protected function getUid()
    {
        if(input('tk')){
            return 1;
        }
        // return 1;
        $token="";
        if (Request::header('token')) {
            $token = Request::header('token');
        }
        if (empty($token)) {
            $token = trim(input("param.token"));
        }
        if(!$token){
            return 0;
        }

        if (Cache("token_" . $token)) {
            if(   !Db::name("iuser")->where("id",Cache("token_" . $token))->value("id")   ){
                return 0;
            }

            return Cache("token_" . $token);
        } else {
            return 0;
        }
    }
    










    /**
     * 自定义重定向方法
     * @param $args
     */
    private function redirectTo(...$args)
    {
        // 此处 throw new HttpResponseException 这个异常一定要写
        throw new HttpResponseException(redirect(...$args));
    }
}
